package com.pug.security.config;

import com.pug.security.file.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @program: xq_pug_alibabacloud_parent
 * @description: jwt+token方式
 * @author: Mr.Ren
 * @create: 2023-07-16 22:09
 **/
@Configuration
@EnableWebSecurity
public class SecurityConfig04 extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    public static final String[] AUTH_WHITELIST = {
            "/user/login",
            "/login/getToken"
            // other public endpoints of your API may be appended to this array
    };



    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                //禁用session，一定要禁止，否则会出现第一次需要token，第二次之后不加token也能访问的情况
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //开启表单验证，借助security自带的工具完成账号密码校验
                .formLogin()
                .and()
                //关闭古老的basic认证方式
                .httpBasic().disable()
                .authorizeRequests()
                //白名单（无需鉴权即可访问）
                .antMatchers(AUTH_WHITELIST).permitAll()
                //匿名访问
                .antMatchers("/login/getToken").anonymous()
                //剩下请求都需要认证才能访问
                .anyRequest().authenticated();

        //配置执行器的顺序
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        //token的验证方式不需要开启csrf的防护
        http.csrf().disable();
    }


    //授权
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //此处配置是基于内存还是基于数据库

        //方式1：基于内存

        //方式2：基于官方推荐H2数据库
        //auth.jdbcAuthentication().dataSource(dataSource);

        //方式3：基于userDetailsService
        auth.userDetailsService(userDetailsService)
                //密码加密
                .passwordEncoder(passwordEncoder());

        //方式4：基于userDetailsService+自定义认证类
//        auth.authenticationProvider(myAuthenticationProvider)
//                .userDetailsService(userDetailsService);
    }

    /**
     * 密码加密工具
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


}
